//
//  BaseService.m
//  YYBG_IOS
//
//  Created by wyl on 2017/2/22.
//  Copyright © 2017年 wyl. All rights reserved.
//

#import "BaseService.h"
#import<CommonCrypto/CommonDigest.h>

//通讯密钥
const static NSString *key = @"FXJ2017@2028";

@implementation BaseService

//获取加密后的url
+(NSString *)getMD5Url:(NSMutableDictionary *)dictionary {
    if (!dictionary) {
        dictionary = [NSMutableDictionary dictionary];
    }
    //默认需要添加的参数
    [dictionary setObject:@"0" forKey:@"UserId"];
    [dictionary setObject:@"iOS" forKey:@"DeviceType"];
//    [dictionary setObject:@"" forKey:@"DeviceKey"];
//    [dictionary setObject:@"SWDFGTRFVG" forKey:@"VerifiCode"];
    [dictionary setObject:[self getCurrentTimestamp] forKey:@"TimeStamp"];
    
    //按照ASCII字典排序
    NSMutableArray *array = [NSMutableArray array];
    for (NSString *key in dictionary) {
        NSString *prarm = [NSString stringWithFormat:@"%@=%@",key,dictionary[key]];
        [array addObject:prarm];
    }
    NSArray *charArray = [array copy];
    NSStringCompareOptions comparisonOptions = NSCaseInsensitiveSearch |NSNumericSearch |NSWidthInsensitiveSearch |NSForcedOrderingSearch;
    NSComparator sort = ^(NSString *obj1,NSString *obj2){
        NSRange range = NSMakeRange(0,obj1.length);
        return [obj1 compare:obj2 options:comparisonOptions range:range];
    };
    NSArray *resultArray2 = [charArray sortedArrayUsingComparator:sort];
    
    //url地址
    NSString *urlString = [resultArray2 componentsJoinedByString:@"&"];
    
    //加密前数据
    NSString *signTemp = [NSString stringWithFormat:@"%@&key=%@",urlString,key];
    //加密后签名 sign
    NSString *signString = [self md5:signTemp];
    
    //加密后的整体url
    NSString *returnString = [NSString stringWithFormat:@"%@&sign=%@",urlString,signString];
    return returnString ;
}

//md5加密
+(NSString *) md5:(NSString *) input {
    if (!input || [input isEqualToString:@""]) {
        return @"";
    }
    const char *cStr = [input UTF8String];
    unsigned char digest[CC_MD5_DIGEST_LENGTH];
    CC_MD5( cStr, strlen(cStr), digest ); // This is the md5 call
    NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
        [output appendFormat:@"%02x", digest[i]];
    return  output;
}
//获取当前时间的时间戳
+(NSString*)getCurrentTimestamp{
    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval a=[dat timeIntervalSince1970];
    NSString*timeString = [NSString stringWithFormat:@"%0.f", a];//转为字符型
    return timeString;
}


@end
